# -*- coding: utf-8 -*-

class TransferOrderController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:transfer_print_header,:transfer_print_footer,:transfer_print_content,:check_stock]

  #显示添加新调拨订单的页面
  def newTransfer
    
  end

  #显示编辑调拨订单的页面
  def editTransfer
    
  end

  #显示审批调拨订单页面
  def auditTransferOrder

  end

  #显示调拨页面
  def transferList
    
  end

  #调拨记录列表
  def transferAuditList

  end

  #得到某一个采购订单的信息
  def getTransferOrderById
    transferOrder = TransferOrder.find(params[:id])
    rootStr = transferOrder.to_json(:include=>{:employee=>{:only=>[:id,:name]},:department=>{:only=>[:id,:name]},:fromWarehouse=>{:only=>[:id,:name]},:toWarehouse=>{:only=>[:id,:name]}})
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr, :layout=>false
  end

  def getAllTransfer
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:from_warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'from_warehouse_id = :from_warehouse_id'
      else
        conditionsStr = conditionsStr+' AND from_warehouse_id = :from_warehouse_id'
      end
      conditionsHash[:from_warehouse_id] = params[:from_warehouse_id].to_i
    end

    if params[:to_warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'to_warehouse_id = :to_warehouse_id'
      else
        conditionsStr = conditionsStr+' AND to_warehouse_id = :to_warehouse_id'
      end
      conditionsHash[:to_warehouse_id] = params[:to_warehouse_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    #显示产品
    if params[:product_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'transfer_order_details.product_id = :product_id'
      else
        conditionsStr = conditionsStr+' AND transfer_order_details.product_id = :product_id'
      end
      conditionsHash[:product_id] = params[:product_id].to_i
    end
    
    count = TransferOrder.countAllTransfer conditionsStr,conditionsHash
    transferOrders = TransferOrder.findAllTransfer conditionsStr,conditionsHash,paramsHash
    
    jsonStr = "{totalProperty:"+count.to_s+",root:"+transferOrders.to_json(:include=>[:employee,:department,:auditor,:fromWarehouse,:toWarehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getAllTransfersByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = "auditing_status like :auditing_status"
    conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"

    if params[:order_number].to_s != ''
      conditionsStr = ' AND seq_number like :order_number'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:from_warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'from_warehouse_id = :from_warehouse_id'
      else
        conditionsStr = conditionsStr+' AND from_warehouse_id = :from_warehouse_id'
      end
      conditionsHash[:from_warehouse_id] = params[:from_warehouse_id].to_i
    end

    if params[:to_warehouse_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'to_warehouse_id = :to_warehouse_id'
      else
        conditionsStr = conditionsStr+' AND to_warehouse_id = :to_warehouse_id'
      end
      conditionsHash[:to_warehouse_id] = params[:to_warehouse_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end
    logger.info conditionsStr
    count = TransferOrder.countAllTransfer conditionsStr,conditionsHash
    transferOrders = TransferOrder.findAllTransfer conditionsStr,conditionsHash,paramsHash
    
    jsonStr="{totalProperty:"+count.to_s+",root:"+transferOrders.to_json(:include=>[:employee,:department,:auditor,:fromWarehouse,:toWarehouse])+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到调拨单的详细信息
  def getTransferOrderDetailsById
    transferOrderDetails = TransferOrderDetail.where(transfer_order_id:params[:transfer_order_id])

    jsonStr="{totalProperty:"+transferOrderDetails.length.to_s+",root:"+transferOrderDetails.to_json(:include=>{:product=>{:only=>[:id,:name,:is_suit,:spec,:number,:unit]}})+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #审批调拨产品，并添加到结算表中。
  def updateAuditingStatus
    transferOrder = TransferOrder.find(params[:transfer_order_id])
    info = nil
    if TransferOrder !=nil
      auditingStatus = params[:auditing_status]
      transferOrder.auditor_id = session[:employee_id]
      transferOrder.audit_opinion =  params[:audit_opinion]
      TransferOrder.transaction do
        if(auditingStatus == "是")
          #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
          ProductCollection.delete_all("resource_type = 'TransferOrder' AND resource_id = #{params[:transfer_order_id]}")
          auditingStatus = Constants::PASS_APPLY_ADD
          transferOrder.auditing_status = auditingStatus
          transferOrder.save
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
          #以下代码作二个功能，一是对于调出的功能是一，对于调入的是加
          transferOrderDetails = transferOrder.transfer_order_details
          transferOrderDetails.each do |transferOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = transferOrder.company_id
            productCollection.department_id = transferOrder.department_id
            productCollection.employee_id = transferOrder.employee_id
            productCollection.warehouse_id = transferOrder.from_warehouse_id
            productCollection.product_id = transferOrderDetail.product_id
            productCollection.quantity = 0 - transferOrderDetail.quantity
            productCollection.description =  transferOrderDetail.description
            productCollection.action_date =  transferOrder.action_date
            productCollection.resource_id =  transferOrder.id
            productCollection.resource_type =  TransferOrder.name
            productCollection.save!
            #以上为减，以下为加
            productCollection = ProductCollection.new
            productCollection.company_id = transferOrder.company_id
            productCollection.department_id = transferOrder.department_id
            productCollection.employee_id = transferOrder.employee_id
            productCollection.warehouse_id = transferOrder.to_warehouse_id
            productCollection.product_id = transferOrderDetail.product_id
            productCollection.quantity = transferOrderDetail.quantity
            productCollection.description =  transferOrderDetail.description
            productCollection.action_date =  transferOrder.action_date
            productCollection.resource_id =  transferOrder.id
            productCollection.resource_type =  TransferOrder.name
            productCollection.save!
          end
        else
          auditingStatus = Constants::REJECT_APPLY_ADD
          transferOrder.auditing_status = auditingStatus
          transferOrder.save
        end

        #结算表处理完毕。
        info = "成功"
      end
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #生成新的调拨单
  def create
    
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    #productHash = paramsHash["products"][0]
    #取得这次入库，到入到哪个库中。
    transferOrder = TransferOrder.new
    transferOrder.company_id = session[:company_id]
    transferOrder.department_id = session[:department_id]
    transferOrder.employee_id = session[:employee_id]
    transferOrder.action_date = paramsHash['action_date']
    transferOrder.from_warehouse_id = paramsHash['from_warehouse_id']
    transferOrder.to_warehouse_id = paramsHash['to_warehouse_id']
    transferOrder.description = paramsHash['description']
    #判断一下当前用户角色是否需求审批
    sysParam =  SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash['temporary'] == '1'
      transferOrder.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_transfer_add == "否"
        transferOrder.auditing_status = Constants::PASS_APPLY_ADD
        transferOrder.deal_with_status = ''
      else
        transferOrder.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end
    
    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      if productHash["product_id"] != ""
        transferOrderDetail = TransferOrderDetail.new
        transferOrderDetail.product_id = productHash["product_id"]
        transferOrderDetail.quantity = productHash["quantity"]
        transferOrder.transfer_order_details << transferOrderDetail
      end
    end

    #开始事务，确保在流水号正常的情况下，保存入库单时,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为销售订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?",session[:company_id],TransferOrder.name).first

        sequence.seq_no = sequence.seq_no + 1
        transferOrder.seq_number = sequence.seq_no
        transferOrder.order_number = sequence.ab + ":" + transferOrder.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        transferOrder.save!

        #判断此时是否已经默认经过审批了，如果经过审批了，就直接把内容更新到汇总表中。
        #如果是默认要经过审批的，则在审批过总，才进入汇总表。
        if paramsHash['temporary'] != '1' && sysParam.audit_for_transfer_add == "否"          
          transferOrderDetails = transferOrder.transfer_order_details
          transferOrderDetails.each do |transferOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = transferOrder.company_id
            productCollection.department_id = transferOrder.department_id
            productCollection.employee_id = transferOrder.employee_id
            productCollection.warehouse_id = transferOrder.from_warehouse_id
            productCollection.product_id = transferOrderDetail.product_id
            productCollection.quantity = 0 - transferOrderDetail.quantity
            productCollection.description =  transferOrderDetail.description
            productCollection.action_date =  transferOrder.action_date
            productCollection.resource_id =  transferOrder.id
            productCollection.resource_type =  TransferOrder.name
            productCollection.save!
            #以上为减法，以下为加法
            productCollection = ProductCollection.new
            productCollection.company_id = transferOrder.company_id
            productCollection.department_id = transferOrder.department_id
            productCollection.employee_id = transferOrder.employee_id
            productCollection.warehouse_id = transferOrder.to_warehouse_id
            productCollection.product_id = transferOrderDetail.product_id
            productCollection.quantity = transferOrderDetail.quantity
            productCollection.description =  transferOrderDetail.description
            productCollection.action_date =  transferOrder.action_date
            productCollection.resource_id =  transferOrder.id
            productCollection.resource_type =  TransferOrder.name
            productCollection.save!
          end
        end
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end
    
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  
  #编辑后的保存
  def update
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    #productHash = paramsHash["products"][0]
    transferOrder = TransferOrder.where("id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status <> ?)",paramsHash['id'],session[:company_id],'通过').first
    begin
      if transferOrder != nil
        transferOrder.company_id = session[:company_id]
        transferOrder.department_id = session[:department_id]
        transferOrder.employee_id = session[:employee_id]
        transferOrder.description = paramsHash['description']
        transferOrder.from_warehouse_id = paramsHash['from_warehouse_id']
        transferOrder.to_warehouse_id = paramsHash['to_warehouse_id']
        transferOrder.description = paramsHash['description']
        transferOrder.audit_opinion = ''
        transferOrder.auditor_id = ''

        #判断一下当前用户角色是否需求审批
        sysParam =  SysParam.find_by_company_id(session[:company_id])

        #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
        if paramsHash['temporary'] == '1'
          transferOrder.deal_with_status = Constants::TEMP_ADD
        else
          if sysParam.audit_for_transfer_add == "否"
            transferOrder.auditing_status = Constants::PASS_APPLY_ADD
            transferOrder.deal_with_status = ''
          else
            transferOrder.auditing_status = Constants::AUDIT_APPLY_ADD
          end
        end

        #products信息
        productsHashArray = paramsHash["products"]
        #在这里，要作一个增，删，编辑操作，以前台数据为准。
        #首先各取出前台与后台的ID数组
        fgIdArray = Array.new
        productsHashArray.each do |productHash|
          fgIdArray << productHash["id"].to_i
        end

        bgIdArray = Array.new
        transferOrderDetails = transferOrder.transfer_order_details
        transferOrderDetails.each do |transferOrderDetail|
          bgIdArray << transferOrderDetail.id
        end

        idIntersectionArray = fgIdArray & bgIdArray
        addIdArray = fgIdArray - idIntersectionArray
        delIdArray = bgIdArray - idIntersectionArray
        TransferOrderDetail.delete(delIdArray)

        #在进行从新整理数据之前，先把采购订单的总金额置“0”
        productsHashArray.each do |productHash|
          #只有当用户选择的产品不为空时，才有详细订单。
          if productHash["product_id"] !=""
            #没Id说明是新增加的。
            if productHash["id"] == ""
              transferOrderDetail = TransferOrderDetail.new
              transferOrderDetail.product_id = productHash["product_id"]
              transferOrderDetail.quantity = productHash["quantity"]
              transferOrderDetail.description = productHash["description"]
              transferOrder.transfer_order_details << transferOrderDetail
            else
              transferOrderDetail = TransferOrderDetail.find(productHash["id"].to_i)
              transferOrderDetail.product_id = productHash["product_id"]
              transferOrderDetail.quantity = productHash["quantity"]
              transferOrderDetail.description = productHash["description"]
              transferOrderDetail.save
            end
          end
        end
        transferOrder.save!

        #判断此时是否已经默认经过审批了，如果经过审批了，就直接把内容更新到汇总表中。
        #如果是默认要经过审批的，则在审批过总，才进入汇总表。
        if params[:temporary] != '1' && sysParam.audit_for_transfer_add == "否"
          #先删除以前的记录，此处处理是为了防止sysparams变化引起多余的数据。
          ProductCollection.delete_all("resource_type = 'TransferOrder' AND resource_id = #{transferOrder.id}")
          transferOrderDetails = transferOrder.transfer_order_details
          transferOrderDetails.each do |transferOrderDetail|
            productCollection = ProductCollection.new
            productCollection.company_id = transferOrder.company_id
            productCollection.department_id = transferOrder.department_id
            productCollection.employee_id = transferOrder.employee_id
            productCollection.warehouse_id = transferOrder.from_warehouse_id
            productCollection.product_id = transferOrderDetail.product_id
            productCollection.quantity = 0 - transferOrderDetail.quantity
            productCollection.description =  transferOrderDetail.description
            productCollection.action_date =  transferOrder.action_date
            productCollection.resource_id =  transferOrder.id
            productCollection.resource_type =  TransferOrder.name
            productCollection.save!
            #以上为减，以下为加
            productCollection = ProductCollection.new
            productCollection.company_id = transferOrder.company_id
            productCollection.department_id = transferOrder.department_id
            productCollection.employee_id = transferOrder.employee_id
            productCollection.warehouse_id = transferOrder.to_warehouse_id
            productCollection.product_id = transferOrderDetail.product_id
            productCollection.quantity = transferOrderDetail.quantity
            productCollection.description =  transferOrderDetail.description
            productCollection.action_date =  transferOrder.action_date
            productCollection.resource_id =  transferOrder.id
            productCollection.resource_type =  TransferOrder.name
            productCollection.save!
          end
        end
      end
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #撤消
  def applyToCancel
    begin
      transferOrder = TransferOrder.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_transfer_cancel == "否"
        transferOrder.auditing_status = Constants::PASS_APPLY_CANCEL
        transferOrder.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'TransferOrder' AND resource_id = #{params[:id]}")
        #如果不需要审批，则把汇总表中的数据设置为is_locked = 1
      else
        transferOrder.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      transferOrder.auditor_id = session[:employee_id]
      transferOrder.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #验证一下当前要调拨的库存数量。
  def check_stock
    paramsHash = Util.paramsPreprocessToHash(params[:data])

    #插入products信息
    productsHashArray = paramsHash["products"]
    products = TransferOrder.checkStockBeforeTransfer(paramsHash["from_warehouse_id"], productsHashArray)
    logger.info products.to_json()
    render :text=>products.to_json(), :layout=>false
  end

  #生成打印销售凭证的头部
  def transfer_print_header
    @transferOrder = TransferOrder.find(params[:id],:include=>[:fromWarehouse,:employee])
  end

  #生成打印销售凭证的内容
  def transfer_print_content
    @transferOrder = TransferOrder.find(params[:id],:include=>[:transfer_order_details,:employee,:fromWarehouse,:toWarehouse])
    @transferOrderDetails = @transferOrder.transfer_order_details
    @totalQuantity = @transferOrderDetails.sum(:quantity)
    logger.info @totalQuantity
  end

  def transfer_print_footer
    @transferOrder = TransferOrder.find(params[:id],:include=>[:transfer_order_details,:fromWarehouse,:toWarehouse])
  end
end
